// routes/user.js
const express = require('express');
const router = express.Router();
const {asyncHandler} = require('../tool/middleWare');
const { authMiddleware, validateRequest} = require('../tool/middleWare');
const {
    registerService,
    updateUserProfileService,
    getAdvisorListService,
    getAdvisorDetailService, getFavoriteAdvisorsPagedService,
} = require('../service/user');
const { query } = require('express-validator');
const express_validate = require('../tool/express_validator');
const {
  favoriteAdvisorService,
  unfavoriteAdvisorService,
  getFavoriteAdvisorsService,
} = require('../service/user');

/*用户注册*/
router.post(
    '/register',
    validateRequest({
       body : {
           phoneNumber: {type: 'string', required: true},
           countryCode: {type: 'string', required: true},
           password: {type: 'string', required: true},
           type: {type: 'number', required: true}
       }
    }),
    asyncHandler(async (req, res) => {
        const { phoneNumber, countryCode, password, type } = req.body;
        const result = await registerService({ phoneNumber, countryCode, password, type });
        // 使用 res.success 统一返回
        res.success(result, '注册成功');
    })
);

/*用户修改信息*/
router.put(
    '/update',
    authMiddleware,
    validateRequest({
        body: {
            name: {type: 'string', required: false},
            dataOfBirth: {type: 'string', required: false},
            gender: {type: 'number', required: false},
            bio: {type: 'string', required: false},
            aboutMe: {type: 'string', required: false}
        }
    }),
    asyncHandler(async (req, res) => {
        const { name, dataOfBirth, gender, bio, aboutMe } = req.body;
        const loginUser = req.loginUser; // 已由 authMiddleware 填充
        const updatedData = await updateUserProfileService({
            id: loginUser.id,
            type: loginUser.type,
            name,
            dataOfBirth,
            gender,
            bio,
            aboutMe,
        });
        res.success(updatedData, '信息已更新');
    })
);

/*获取顾问列表*/
router.get(
    '/advisors/list',
    validateRequest({
        query: {
            pageSize: {type: 'number', required: false},
            offset: {type: 'number', required: false}
        }
    }),
    asyncHandler(async (req, res) => {
        // 保证传入的分页参数是数字或由 service 处理
        const { pageSize, offset } = req.query;
        const result = await getAdvisorListService({ pageSize, offset });
        res.success(result);
    })
);

/*顾问主页展示*/
router.get(
    '/advisor/infShow',
    validateRequest({
        query: {
            id: {type: 'number', required: true}
        }
    }),
    asyncHandler(async (req, res) => {
        const { id } = req.query;
        const result = await getAdvisorDetailService(id);
        res.success(result);
    })
);


/*用户收藏顾问*/
router.get(
  '/favorite/add',
  authMiddleware,
  query('advisorId').isInt({ min: 1 }).toInt(),
  query('note').optional().isString().trim().isLength({ max: 100 }),
  express_validate,
  asyncHandler(async (req, res) => {
    const userId = req.loginUser.id;
    const { advisorId, note } = req.query;
    const data = await favoriteAdvisorService({ userId, advisorId, note });
    res.success(data, '收藏成功');
  })
);

/*取消收藏顾问*/
router.get(
  '/favorite/remove',
  authMiddleware,
  query('advisorId').isInt({ min: 1 }).toInt(),
  express_validate,
  asyncHandler(async (req, res) => {
    const userId = req.loginUser.id;
    const { advisorId } = req.query;
    const data = await unfavoriteAdvisorService({ userId, advisorId });
    res.success(data, '已取消收藏');
  })
);

/*查看收藏的顾问列表*/
router.get(
  '/favorite/list',
  authMiddleware,
  // 允许多种分页参数存在，但不强制必须；由 Service 统一兜底
  query('page').optional().isInt({ min: 1 }).toInt(),
  query('pageSize').optional().isInt({ min: 1 }).toInt(),
  query('offset').optional().isInt({ min: 0 }).toInt(),
  query('limit').optional().isInt({ min: 1 }).toInt(),
  query('limite').optional().isInt({ min: 1 }).toInt(), // 兼容拼写
  express_validate,
  asyncHandler(async (req, res) => {
    const userId = req.loginUser.id;

    const {
      page,
      pageSize,
      offset,
      limit,
      limite, // 兼容
    } = req.query;

    const data = await getFavoriteAdvisorsPagedService(userId, {
      page,
      pageSize,
      offset,
      limit,
      limite,
    });

    res.success(data, '获取收藏列表成功');
  })
);


module.exports = router;